package com.inspector.app.ui.flight

import android.app.ProgressDialog
import android.content.Intent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.inspector.app.BuildConfig
import com.inspector.app.R
import com.inspector.app.databinding.FlightMapControlBinding
import com.inspector.app.di.location.LocationInstance
import com.inspector.app.ui.flight.maplayer.SwitchMapLayerFragment
import com.inspector.app.ui.plot.PlotActivity
import com.inspector.app.util.ConstantUtil
import com.inspector.app.util.LogUtil
import com.inspector.app.util.SharedPreferencesUtils
import com.mapsforge.map.EfbLatLngPoint
import com.mapsforge.map.EfbMap
import com.mapsforge.map.vtm.AppExecutors
import com.mapsforge.map.vtm.VtmEfbMap
import com.mapsforge.map.vtm.VtmEfbMapView
import com.mapsforge.org.oscim.map.DJMap
import com.mapsforge.org.oscim.map.IDJMap
import java.lang.ref.WeakReference


/**
 * 地图相关
 */
class MapLifecycleObserver: DefaultLifecycleObserver {

    private val TAG: String = MapLifecycleObserver::class.java.simpleName


    private var vtmEfbMapView: VtmEfbMapView? = null
    val efbMap: EfbMap get() = vtmEfbMapView!!.map
    val dMap: IDJMap get() = vtmEfbMapView!!.dMap

    fun setupView(fragment: Fragment, viewStubInflate: View, mapControl: FlightMapControlBinding) {
        onDestroyView()

        //[初始化地图]
        val efbMapView = setupMapView(viewStubInflate).also {
            vtmEfbMapView = it
        }

        //[地图控制相关点击事件]
        mapControl.imMapLocation.setOnClickListener {
            setMapPosition(efbMapView)
        }

        mapControl.imMapZoomin.setOnClickListener {
            efbMapView.map.zoomIn()
        }

        mapControl.imMapZoomout.setOnClickListener {
            efbMapView.map.zoomOut()
        }

        //[地图搜索]
        mapControl.mapSearch.setOnClickListener {
            try {
                fragment.startActivity(Intent(fragment.requireContext(), PlotActivity::class.java))
//                fragment.findNavController().navigate(R.id.action_to_plot)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        //[切换图层]
        mapControl.switchMapLayer.setOnClickListener {
            switchMapLayer(fragment, it)
        }
    }

    private fun setupMapView(inflate: View): VtmEfbMapView {
        LogUtil.e(TAG, "加载地图 setupView")
        val efbMapView = inflate.findViewById<VtmEfbMapView>(R.id.efbMapView)
        efbMapView.setupView(ConstantUtil.BASE_DIR, BuildConfig.TianDiTuAppKey)

        // TODO: 夜间模式
//        efbMapView.map.setTheme(EfbMap.MapThemes.DEFAULT)

        //[默认 矢量图层]
        val vectorLayerIndex = EfbMap.MapType.entries.toMutableList().indexOf(EfbMap.MapType.Vector)
        val lastCheckedPos = SharedPreferencesUtils.getInt(ConstantUtil.USERID, ConstantUtil.MAP_LAYER_TYPE, vectorLayerIndex)
        val mapType = EfbMap.getMapTypeByIndex(lastCheckedPos)

        //[默认设置天地图矢量图图层]
        val finalMapType = if ((efbMapView.map as VtmEfbMap).layerNeedDownload(mapType)) {
            EfbMap.MapType.T_Vector
        } else {
            mapType
        }
        efbMapView.map.mapType = finalMapType

        val mapLayerIndex = EfbMap.MapType.entries.toMutableList().indexOf(finalMapType)
        SharedPreferencesUtils.put(ConstantUtil.USERID, ConstantUtil.MAP_LAYER_TYPE, mapLayerIndex)

        setMapPosition(efbMapView)
        return efbMapView
    }


    /**
     * 点击定位功能
     */
    private fun setMapPosition(efbMapView: VtmEfbMapView) {
        val location = LocationInstance.getInstance().lastKnownLocation?: return
        (efbMapView.map as VtmEfbMap).setPostion(EfbLatLngPoint(location.latitude, location.longitude))
    }


    /**
     * 切换图层
     */
    private var loadingRef: WeakReference<ProgressDialog>? = null
    private fun switchMapLayer(fragment: Fragment, view: View) {
        SwitchMapLayerFragment.create(view) { _, item ->
            if (item == null) return@create
            loadingRef?.get()?.dismiss()
            loadingRef?.clear()
            loadingRef = null
            val loadingDialog =
                ProgressDialog.show(fragment.requireContext(), "", "正在尽全力切换图层...", true)
            loadingRef = WeakReference(loadingDialog)

            AppExecutors.getInstance().diskIO().execute {
                if (!(efbMap as VtmEfbMap).layerNeedDownload(item.mapType) { succeed ->
                        if (loadingDialog.isShowing) {
                            loadingDialog.dismiss()
                        }
                        if (succeed) {
                            AppExecutors.getInstance().mainThread().execute {
                                efbMap.mapType = item.mapType
                            }
                        }
                }) {
                    if (loadingDialog.isShowing) {
                        loadingDialog.dismiss()
                    }
                    efbMap.mapType = item.mapType
                }
            }
        }.show(fragment.childFragmentManager, null)
    }



    //============================ [生命周期部分 start] ============================
    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        vtmEfbMapView?.onResume()
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        vtmEfbMapView?.onPause()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        onDestroyView()
        super.onDestroy(owner)
    }

    private fun onDestroyView() {
        vtmEfbMapView?.onDestroy()
        vtmEfbMapView = null
    }

}